
import logging
log = logging.getLogger('level')
log.debug("imported")
 
import data
import config
from common import *
from constants import *
from cocos.euclid import *
import cocos
log.debug("libs imported")

from tile_layer import TileHandeler, TileLayer, load_level_from_image  
from lookup import BuildLookupTable,SortByName, SortByTile
from filedef import NPC    
import npc_sprite
from bg_layer import BGLayer

log.debug("finished imports")

class Level(TileHandeler):
    monster_def             = "defs/testnpc.def"
    static_def              = "defs/static.def"
    tile_images_bg          = "images/tile.png"
    tile_images             = "images/dngn.png"
    creature_tile_images    = "images/nethackcreaturetiles32x32.png" 
    level_layout            = "level/test1.tga"
    
    is_event_handler = True    
    
    def __init__(self, player, level_def = None):
        super(Level, self).__init__()
        
        if level_def is not None:
            self.name = level_def.name
            self.monster_def = level_def.monster_def
            self.static_def = level_def.static_def
            self.tile_images_bg = level_def.tile_images_bg
            self.tile_images = level_def.tile_images
            self.creature_tile_images = level_def.creature_tile_images
            self.level_layout = level_def.level_layout
            self.player_def = level_def.player_def
                       
        self.NPCs = BuildLookupTable("mob", self.monster_def) 
        self.NPCs = BuildLookupTable("mob", self.static_def) 
        
        # replace with tiles
        self.distance = cocos.layer.ScrollableLayer(parallax = 0.2)
        self.distance.add(BGLayer("TEMP_GAMEBG"))
        
        self.leveldata = load_level_from_image(self.level_layout)
 
        self.back_layer = TileLayer(self.leveldata, self.tile_images_bg, [32,32], True)
        self.back_layer.parallax = 1.0
        
        self.game_layer = TileLayer(self.leveldata, self.tile_images, [32,32])
        
        self.bg_mobs,self.fg_mobs, self.player_start, extras = npc_sprite.CreateMobsFromLevel(self.leveldata, SortByTile(self.NPCs), [32,32])
        
        for mob in self.fg_mobs:
            self.game_layer.add(mob)
        for ex in extras:
            self.game_layer.add(ex)
        for mob in self.bg_mobs:
            self.back_layer.add(mob)
        
        #self.ALL_MOBS = [weakref.ref(mob) for mob in self.fg_mobs + self.bg_mobs]
        self.ALL_MOBS = self.fg_mobs + self.bg_mobs
        
        #TODO: replace with tiles
        #self.foreground = cocos.layer.ScrollableLayer(parallax = 1.3)
        #bg = BGLayer("TEMP_GAMEFG")
        #bg.do(cocos.actions.FadeTo(0.3, 1))
        #self.foreground.add(bg)
            
        #Distance (scenery)
        self.scroller.add(self.distance, z= -8)
       
        #Close background (spider webs?)
        self.scroller.add(self.back_layer, z= -6)
        
        #Player layer (wall textures + most NPC) 
        self.scroller.add(self.game_layer, z= -5)
        
        #Foreground - in front of player (alpha when player collides)
        #self.scroller.add(self.foreground, z= -4)

        if self.player_start is None:
            log.info("Missing player start")
            self.player_start = [100,100]
            
            
        # not sure we need to keep a handle on this guy down this low
        player.position = self.player_start
        self.game_layer.add(player)
        
        self.camera_loc = Vector2(player.position[0],player.position[1])  
        self.camera_focus = self.camera_loc   
        
        #self.player = player 
        self.schedule(self.update)
        
    def set_mouse(self, mouse):
        self.game_layer.add(mouse)
            
    def set_focus(self, x, y):
        self.camera_focus = Vector2(x,y) 
        log.debug("set_focus "+str(self.camera_focus))
        #self.sprite.do( Lerp("x", 0, x, 10) )
    
    def refocus(self,dt):     
        diff = self.camera_focus - self.camera_loc  
        d = diff.magnitude() 
        
        
        diff.normalize()
        diff *= d / 10.0
        if d > 10:
            
            self.camera_loc += diff
            
        self.scroller.set_focus(self.camera_loc.x, self.camera_loc.y)
            
    def update(self, dt):
        self.refocus(dt)
        for mob in self.fg_mobs:
            mob.update(dt)
        for mob in self.bg_mobs:
            mob.update(dt)

    def collide(self, player):
        player.check_collide(self.game_layer)
        
    def set_player_start(self, pos):
        self.player_start = pos
        
def run(moo):
    from player import UserControlledSprite
    from mouse import  MouseManager
    import anims
    main_scene = cocos.layer.Layer()
    res = anims.GetFramesFromFile("images/nethackcreaturetiles32x32.png", [32,32])
    player = UserControlledSprite(main_scene, res[33], [200,200], None)
    
    level = Level(player)
    #TODO: MESSY!!
    mouse = MouseManager(player, level.scroller)

    main_scene.add(level)

    return main_scene
